package com.youlu.campus.service.douyin;


import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.douyin.DouYinUserWatchVideo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Service
public class DouYinUserWatchVideoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public Boolean watchVideoByActivityId(String activityId, UserPO currentUser){
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(currentUser.getId()));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        DouYinUserWatchVideo douYinUserWatchVideo = this.mongoTemplate.findOne(query, DouYinUserWatchVideo.class);
        if(Objects.nonNull(douYinUserWatchVideo)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }


    public DouYinUserWatchVideo findByActivityId(String activityId, UserPO currentUser){
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(currentUser.getId()));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        DouYinUserWatchVideo douYinUserWatchVideo = this.mongoTemplate.findOne(query, DouYinUserWatchVideo.class);
        if(Objects.nonNull(douYinUserWatchVideo)){
            return douYinUserWatchVideo;
        }
        Update update = new Update();
        Date now  = new Date();
        update.setOnInsert("createdTime",now);
        update.set("updatedTime",now);
        update.set("openId",currentUser.getOpenId());
        update.set("unionId",currentUser.getUnionId());
        FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
        findAndModifyOptions.returnNew(Boolean.TRUE);
        findAndModifyOptions.upsert(Boolean.TRUE);
        return this.mongoTemplate.findAndModify(query,update,findAndModifyOptions,DouYinUserWatchVideo.class);
    }
}
